<?php
use app\assets\PublishAsset;
use yii\helpers\Html;
use yii\helpers\Url;

PublishAsset::register($this);
?>

<?php $this->beginPage() ?>
    <!DOCTYPE html>
    <html lang="<?= Yii::$app->language ?>">
    <head>
        <meta charset="<?= Yii::$app->charset ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?= Html::csrfMetaTags() ?>
        <title>编辑修改商品</title>
        <?php $this->head() ?>
    </head>
    <body>
    <?php $this->beginBody() ?>

    <style>

        .attrName{
            margin-top: 10px;
            font-size:15px;
        }

        .attributeSet{
            margin-left: -7px;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .attributeSet:hover{


        }

        .categorySet{
            margin-left: -7px;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .sku_del{

            display: none;
            position: absolute;
            width: 20px;
            height: 20px;
            margin-left: -10px;
            margin-top: -6px;
            background-color: #00438A;
            background: url('https://d.weidian.com/images/items/icon_del3.png') no-repeat;

        }

        .img_del{

            display: none;
            position: absolute;
            width: 20px;
            height: 20px;
            margin-left: 115px;
            margin-top: 0;
            background-color: #00438A;
            background: url('https://d.weidian.com/images/items/icon_del3.png') no-repeat;

        }

        .category_del{

            display: none;
            position: absolute;
            width: 20px;
            height: 20px;
            margin-left: -10px;
            margin-top: -8px;
            background-color: #00438A;
            background: url('https://d.weidian.com/images/items/icon_del3.png') no-repeat;

        }

        .labelName{

            width: 80px;

        }

        .divName{
            margin-left: 80px;
            margin-top: -26px;

        }

        .btn1{position: relative;overflow: hidden;margin-top: 5px;margin-right: 4px;display:inline-block;*display:inline;padding:4px 10px 4px;font-size:14px;line-height:18px;*line-height:20px;color:#fff;text-align:center;vertical-align:middle;cursor:pointer;background-color: #337ab7;border:1px solid #cccccc;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
        .btn1 input {position: absolute;top: 0; right: 0;margin: 0;border: solid transparent;opacity: 0;filter:alpha(opacity=0); cursor: pointer;}



        .datagrid-cell, .datagrid-cell-group, .datagrid-header-rownumber, .datagrid-cell-rownumber {
            overflow: visible !important;
        }

    </style>

    <div id="basicInfo">
        <form class="form-horizontal"  id="basicInfoForm">
            <fieldset>
                <div id="legend" class="">
                    <legend class="">编辑修改商品</legend>
                </div>

                <div class="form-group col-md-12">
                    <label for="" class="control-label labelName">商品分类:</label>
                    <div class="divName">
                        <div class="col-md-3 col-sm-3" >
                            <select name="" id="chooseCategorySelect" class="col-md-1 form-control" onchange="getValue(this)">
                            </select>
                        </div>
                        <div class="col-md-3 col-sm-3" >
                            <select name="" id="categorySelect" class="col-md-1 form-control" onchange="getCategory(this)">
                            </select>
                        </div>

                        <div class="col-md-2 col-sm-2" >
                            <p class="btn  btn-default" id="addCategoryBtn"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加</p>
                        </div>
                    </div>
                </div>


                <div id="commodityDiv" >

                    <div class="form-group col-md-12">
                        <label for="commodity_name" class="control-label labelName">商品名称:</label>
                        <div class="divName">
                            <div class="col-md-8 col-sm-8">
                                <input type="text" class="form-control " id="commodity_name" name="commodity_name" check-type="required" value="<?= Html::encode($model->commodity_name) ?>">
                            </div>
                        </div>
                    </div>


                    <div class="form-group col-md-12">
                        <label for="commodity_price" class="control-label labelName">商品价格:</label>
                        <div class="divName">
                            <div class="col-md-3 col-sm-3">
                                <input type="text" class="form-control " id="commodity_price" name="commodity_price" check-type="required figure"  value="<?= Html::encode($model->price) ?>" >
                            </div>
                        </div>
                    </div>

                    <div class="form-group col-md-12">
                        <label for="commodity_postage_template" class="control-label labelName">运费模板:</label>
                        <div class="divName" >
                            <div class="col-md-9 col-sm-9">
                                <span id="postageTemplate" value="<?= Html::encode($model->postage_template_id) ?>"><?= Html::encode($postage_template_name) ?></span>
                                <span id="postageTemplateErrorMessage" style="display: none">请输入内容</span>
                                <p class="btn btn-primary"  id="choosePostageTemplateBtn">设定运费模板</p>
                            </div>
                        </div>
                    </div>

                    <div class="form-group col-md-12">
                        <label for="commodity_price" class="control-label labelName">商品规格:</label>
                        <div class="divName" >
                            <div class="col-md-9 col-sm-9">
                                <div id="rankDiv">
                                </div>
                                <p class="btn btn-primary"  id="addRank">设定多级规格</p>
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-12">
                        <label for="stock_num" class="control-label labelName">商品总数:</label>
                        <div class="divName">
                            <div class="col-md-3 col-sm-3">
                                <input type="text" class="form-control " id="stock_num" name="stock_num" check-type="required number" value="<?= Html::encode($model->stock_num) ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-12">
                        <label for="commodity_code" class="control-label labelName">商品条码:</label>
                        <div class="divName">
                            <div class="col-md-8 col-sm-8">
                                <input type="text" class="form-control " id="commodity_code" name="commodity_code" value="<?= Html::encode($model->pro_id) ?>" >
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-12">
                        <label  class="control-label labelName">橱窗推荐:</label>
                        <div class="divName">
                            <div class="col-md-8 col-sm-8">
                                <input type="checkbox" id="is_hot" style="width: 15px; vertical-align:middle; margin:auto;height:30px; padding:0;">
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-12">
                        <label for="commodity_price" class="control-label labelName">商品图片(拖动交换顺序):</label>
                        <div class="divName" >
                            <div  style="width: 150px;height: 170px;">
                                <input type="file" style="opacity:0;">
                                <i class="img_del"></i>
                                <img class="img-rounded " id="img1" style="width: 120px;height: 120px;margin-left: 15px;"
                                     src="http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"
                                     draggable="true" ondragstart="drag(event)"
                                     ondrop="drop(event)" ondragover="allowDrop(event)" alt="">
                                <div style="text-align: center;">
                                    <div class="btn1" id="btn1">
                                        <span>点击上传</span>
                                        <input id="fileupload1" type="file" name="mypic">
                                    </div>
                                </div>
                            </div>
                            <div style="margin-left: 150px;margin-top: -170px;width: 150px;height: 170px;">
                                <input type="file" style="opacity:0;">
                                <i class="img_del"></i>
                                <img class="img-rounded" id="img2" style="width: 120px;height: 120px;margin-left: 15px;"
                                     src="http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"
                                     draggable="true" ondragstart="drag(event)"
                                     ondrop="drop(event)" ondragover="allowDrop(event)" alt="">
                                <div style="text-align: center;">
                                    <div class="btn1" id="btn2">
                                        <span>点击上传</span>
                                        <input id="fileupload2" type="file" name="mypic">
                                    </div>
                                </div>
                            </div>
                            <div style="margin-left: 300px;margin-top: -170px;width: 150px;height: 170px;">
                                <input type="file" style="opacity:0;">
                                <i class="img_del"></i>
                                <img class="img-rounded" id="img3" style="width: 120px;height: 120px;margin-left: 15px;"
                                     src="http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"
                                     draggable="true" ondragstart="drag(event)"
                                     ondrop="drop(event)" ondragover="allowDrop(event)" alt="">
                                <div style="text-align: center;">
                                    <div class="btn1" id="btn3">
                                        <span>点击上传</span>
                                        <input id="fileupload3" type="file" name="mypic">
                                    </div>
                                </div>
                            </div>
                            <div style="margin-left: 450px;margin-top: -170px;width: 150px;height: 170px;">
                                <input type="file" style="opacity:0;">
                                <i class="img_del"></i>
                                <img class="img-rounded" id="img4" style="width: 120px;height: 120px;margin-left: 15px;"
                                     src="http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"
                                     draggable="true" ondragstart="drag(event)"
                                     ondrop="drop(event)" ondragover="allowDrop(event)" alt="">
                                <div style="text-align: center;">
                                    <div class="btn1" id="btn4">
                                        <span>点击上传</span>
                                        <input id="fileupload4" type="file" name="mypic">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-12">
                        <label  class="control-label labelName">商品描述:</label>
                        <!--            加载富文本-->
                        <div class="divName ">
                            <div class="col-md-10 col-sm-10">
                                <script type="text/plain" id="myEditor" style="width:100%;height:240px;">
                            </script>
                            </div>
                        </div>
                    </div>

                    <div class="form-group col-md-10">
                        <center>
                            <p id="publishBtn" class="btn btn-primary publishBtn">确认修改</p>
                        </center>
                    </div>

                </div>
            </fieldset>
        </form>
    </div>

    <!-- 添加的分类Modal 提示框-->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >添加分类信息</h4>
                </div>
                <div id="addForm">
                    <div class="modal-body">
                        <div class="form-group">
                            <div>
                                <select name="" id="modalChooseCategorySelect" class="form-control" >
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="category_name_input" class="control-label">分类名称:</label>
                            <input type="text" class="form-control" id="category_name_input" name="category_name_input" check-type="required" >
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  id="addBtn">确定添加</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 选择运费模板Modal 提示框-->
    <div class="modal fade" id="choosePostageTemplateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >选择运费模板</h4>
                </div>
                <div id="postageTempalteForm">
                    <div class="modal-body" >
                        <div class="form-group">
                            <select id="postageTemplates" class="form-control" >
                            </select>
                            <div>
                                <div id="postageTemplateDetail">
                                    <table id="postageTemplateDetailTable">
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  id="surePostageTemplateBtn">确定选择</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 选择规格Modal 提示框-->
    <div class="modal fade" id="rankModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >选择多级规格</h4>
                </div>
                <div id="rankForm">
                    <div class="modal-body" >
                        <div class="form-group">
                            <div class="categorySetDiv" >

                            </div>

                            <div class="input-group col-md-5 col-sm-5" style="padding-top: 15px;padding-bottom: 20px">
                                <input type="text" class="form-control categoryInput" placeholder="请输入商品属性">
                            <span class="input-group-btn">
                                <button class="btn btn-default newCategoryBtn" type="button">新建</button>
                            </span>
                            </div>
                            <span style="display: none" id="category_id_span"></span>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  id="sureCategoryBtn">确定添加</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除的Modal 提示框-->
    <div class="modal fade" id="removeAttrModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >删除操作</h4>
                </div>
                <div class="modal-body" >
                    <input type="text" name="" id="attr_id_input" style="display: none">

                    <p style="color: red">是否确定删除，一旦删除后不可恢复</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary"  id="removeAttrBtn">确定删除</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="removeAttrOptModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >删除操作</h4>
                </div>
                <div class="modal-body" >
                    <input type="text" name="" id="attr_opt_id_input" style="display: none">

                    <p style="color: red">是否确定删除，一旦删除后不可恢复</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary"  id="removeAttrOptBtn">确定删除</button>
                </div>
            </div>
        </div>
    </div>


    <p id="attr_p" style="display:none;"><?= Html::encode($model->attr_opt_id) ?></p>

    <input id="content_p" style="display:none;"  value="<?= Html::encode($model->content) ?>">
    <input id="url_arr" style="display:none;"  value="<?= Html::encode($model->banner_url) ?>">
    <input id="commodity_id_input" style="display:none;"  value="<?= Html::encode($model->commodity_id) ?>">
    <input id="is_sale_input" style="display:none;"  value="<?= Html::encode($model->is_sale) ?>">


    <script type="text/javascript">
        $(function () {
            var btn1 = $("#btn1 span");
            $("#fileupload1").wrap("<form id='myupload1' action='../../vendor/edit.php' method='post' enctype='multipart/form-data'></form>");
            $("#fileupload1").change(function(){
                $("#myupload1").ajaxSubmit({
                    dataType:  'json',
                    beforeSend: function() {
                        btn1.html("上传中");
                        $('#img1').prev().css("display","none");
                    },
                    success: function(data) {
                        console.log('data'+data);
                        if(data['url']){
                            $('#img1').attr('src',data['url']);
                            $('#img1').prev().css("display","inline");
                            btn1.html("上传成功");
                        }
                    },
                    error:function(xhr){
                        alert(xhr['responseText']);
                        console.log(xhr);
                        btn1.html("上传失败");
                    }
                });
            });
            var btn2 = $("#btn2 span");
            $("#fileupload2").wrap("<form id='myupload2' action='../../vendor/edit.php' method='post' enctype='multipart/form-data'></form>");
            $("#fileupload2").change(function(){
                $("#myupload2").ajaxSubmit({
                    dataType:  'json',
                    beforeSend: function() {
                        btn2.html("上传中");
                        $('#img2').prev().css("display","none");
                    },
                    success: function(data) {
                        if(data['url']) {
                            $('#img2').attr('src', data['url']);
                            console.log(data);
                            $('#img2').prev().css("display", "inline");
                            btn2.html("上传成功");
                        }
                    },
                    error:function(xhr){
                        alert(xhr['responseText']);
                        console.log(xhr);
                        btn2.html("上传失败");
                    }
                });
            });
            var btn3 = $("#btn3 span");
            $("#fileupload3").wrap("<form id='myupload3' action='../../vendor/edit.php' method='post' enctype='multipart/form-data'></form>");
            $("#fileupload3").change(function(){
                $("#myupload3").ajaxSubmit({
                    dataType:  'json',
                    beforeSend: function() {
                        btn3.html("上传中");
                        $('#img3').prev().css("display","none");
                    },
                    success: function(data) {
                        if(data['url']){
                        $('#img3').attr('src',data['url']);
                        console.log(data);
                        $('#img3').prev().css("display","inline");
                        btn3.html("上传成功");
                        }
                    },
                    error:function(xhr){
                        alert(xhr['responseText']);
                        console.log(xhr);
                        btn3.html("上传失败");
                    }
                });
            });
            var btn4 = $("#btn4 span");
            $("#fileupload4").wrap("<form id='myupload4' action='../../vendor/edit.php' method='post' enctype='multipart/form-data'></form>");
            $("#fileupload4").change(function(){
                $("#myupload4").ajaxSubmit({
                    dataType:  'json',
                    beforeSend: function() {
                        btn4.html("上传中");
                        $('#img4').prev().css("display","none");
                    },
                    success: function(data) {
                        if(data['url']) {
                            $('#img4').attr('src', data['url']);
                            console.log(data);
                            $('#img4').prev().css("display", "inline");
                            btn4.html("上传成功");
                        }
                    },
                    error:function(xhr){
                        alert(xhr['responseText']);
                        console.log(xhr);
                        btn4.html("上传失败");
                    }
                });
            });

            $("body").on('click','.img_del',function(){
                //显示占位图
                $(this).next().attr('src','http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg');
//                $("#btn1 span").html("点击上传");
                $(this).next().next().children('span').html("点击上传")
                $(this).css("display","none");

            });


//            //删除图标显示hover事件
//            $("body").on('mouseover mouseout','.img-rounded',function(){
//                if(event.type == "mouseover"){
//                    //鼠标悬浮
//                    $(this).prev().css("display","inline");
//                }else if(event.type == "mouseout"){
//                    //鼠标离开
//                    $(this).prev().css("display","none");
//
//                }
//            });

            $url_arr = jQuery.parseJSON($('#url_arr').val());

            for (var i=0;i<$url_arr.length;i++){
                $img= "#img"+(i+1);
                $($img).attr('src',$url_arr[i]);
                $btnName="#btn"+(i+1)+" "+"span";
                $($btnName).html("修改图片");
                $($img).prev().css("display","inline");
            }
        });
    </script>


    <script type="text/javascript">


        //加载是否最热
        if(<?= Html::encode($model->is_hot) ?>){

            $('#is_hot').attr('checked','true')

        }else{
            $('#is_hot').removeAttr('checked')

        }

        UM.getEditor('myEditor').setContent($('#content_p').val(),false,false);

        //加载一级二级目录
        $.ajax({
            url:"first-category-list",
            dataType: "json",
            success: function (data) {
                $.each(data,function(){
                    console.log(this['category_id']+this['category_name']);
                    $('#chooseCategorySelect').append('<option value='+this['category_id']+'>'+this['category_name']+'</option>');
                    $('#modalChooseCategorySelect').append('<option value='+this['category_id']+'>'+this['category_name']+'</option>');

                    $('#chooseCategorySelect').val(<?= Html::encode($model->first_category) ?>);//设置默认选中
                    $('#modalChooseCategorySelect').val(<?= Html::encode($model->first_category) ?>);//设置默认选中
                });

            }
        });

        //加载二级目录
        $.get(
            "second-category-list",
            {pid:<?= Html::encode($model->first_category) ?>},
            function (data,status){
                if (status) {
                    $.each(data, function () {
                        console.log(this['category_id'] + this['category_name']);
                        $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                    });

                    $('#categorySelect').val(<?= Html::encode($model->second_category) ?>);//设置默认选中

                    $('#category_id_span').html(<?= Html::encode($model->second_category) ?>);

                    initCategory(<?= Html::encode($model->second_category) ?>);

                }else{
                    alert('分类目录加载失败,请刷新');
                }
            },
            "json"
        );

        //初始化默认分类下的属性
        function initCategory(category_id){
            //加载属性可选择项目
            $.ajax({
                url: "get-attr-list-by-category-id",
                data:{"category_id":category_id},
                dataType: "json",
                success: function (data) {
                    $.each(data,function(){
                        console.log(this['attr_name']+this['attr_id']);
                        $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id'+this['attr_id']+'>'+this['attr_name']+'</span> <i class="category_del"></i> </p>');
                    });
                }
            });

        }

        $attr_opt = jQuery.parseJSON($('#attr_p').html());

        for (var i=0;i<$attr_opt.length;i++) {
            //加载默认属性可选择项目
            $.ajax({
                url: "get-attr-opt-list-by-attr-id",
                data: {"attr_id": $attr_opt[i][0]},
                dataType: "json",
                success: function (data) {
                    var strl = '<div><p class="attrName" id=attr_id_p' + data[0]['attr_id'] + '>' + data[0]['attr_name'] + '</p><div class="attributeSetDiv col-sm-12 col-md-12" style="margin-left: -15px;">';
                    console.log(data);
                    $.each(data, function () {
                            var str = '<p class="label attributeSet"> <span class="btn btn-default attributeBtn" id=attr_opt_id' + this['attr_opt_id'] + '>' + this['attr_opt_name'] + '</span> <i class="sku_del" ></i> </p>';
                            strl += str;
                            console.log(this['attr_opt_name'] + '---->' + str);
                    });
                    $('#rankDiv').append(strl + '</div> <div class="input-group col-md-3 col-sm-3" style="padding-top: 15px;padding-bottom: 20px"> <input type="text" class="form-control attributeInput" placeholder="请输入商品属性" > <span class="input-group-btn"> <button class="btn btn-default newAttributeBtn" type="button" >新建</button> </span></div> </div>');
                    console.log('之前已选择---》' + data[0]['attr_name']);

                    //选中状态遍历
                    ChooseAttrOpt();

                }
            });

        }

        //加载完毕选择已有的属性
        function ChooseAttrOpt(){

            for (var i=0;i<$attr_opt.length;i++) {

                var choose_attr_opt=""+$attr_opt[i]+"";
                var array= choose_attr_opt.split(",");
                console.log(array);

                $('.attributeBtn').each(function(){
                    $attr_opt_id=$(this).attr('ID').substr(11);
                    if($.inArray($attr_opt_id, array)==-1){
                    }else{
                        $(this).addClass('btn-info');
                    }
                });

                console.log('$choose_attr_opt-->'+array);


            }

        }

        //第一级分类取值，获取相应的商品规格属性
        function getValue(obj) {
            console.log(obj.options[obj.selectedIndex].text);
            console.log(obj.options[obj.selectedIndex].value);

            $("#categorySelect").empty();
            //清空属性表
            $('#rankDiv').children().remove();
            $('.categorySetDiv').children().remove();

            $.get(
                "second-category-list",
                {pid:obj.options[obj.selectedIndex].value},
                function (data,status){
                    if (status) {
                        $.each(data, function () {
                            console.log(this['category_id'] + this['category_name']);
                            $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                        });
                        console.log('二级分类加载成功');

                    }else{
                        alert('网络错误,请重试');
                    }
                },
                "json"
            );

        }

        //第二级分类取值，获取相应的商品规格属性
        function getCategory(obj) {
            console.log(obj.options[obj.selectedIndex].text);

            //清空属性表
            $('#rankDiv').children().remove();
            $('.categorySetDiv').children().remove();

            $category_id = $("#categorySelect").val();
            console.log('category_id--->'+$category_id);

            $('#category_id_span').html($category_id);

            //加载属性可选择项目
            $.ajax({
                url: "get-attr-list-by-category-id",
                data:{"category_id":$category_id},
                dataType: "json",
                success: function (data) {
                    $.each(data,function(){
                        console.log(this['attr_name']+this['attr_id']);
                        $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id'+this['attr_id']+'>'+this['attr_name']+'</span> <i class="category_del"></i> </p>');
                    });
                }
            });

        }

        //点击添加分类的按钮事件弹出框
        $('#addCategoryBtn').click(function() {
            $('#addModal').modal();
        });

        //确定添加分类按钮
        $('#addBtn').click(function() {

            //正则提示写法
            if ($("#addForm").valid()==false){
                alert('填写信息有误,请检查');
                return false;
            }

            var value = $("#modalChooseCategorySelect option:selected").val();
            console.log('$("#modalChooseCategorySelect option:selected").val()'+$("#modalChooseCategorySelect option:selected").val());

            $.get(
                "add-second-category",
                {pid:value,category_name:$('#category_name_input').val()},
                function (data,status){
                    if (status) {

                        console.log('data--->'+data);

                        if(data==='0'){
                            alert('填写信息有误,请检查');
                        }else{
                            $("#chooseCategorySelect").val(value);
                            $("#categorySelect").empty();

                            $.each(data, function () {
                                console.log(this['category_id'] + this['category_name']);
                                $('#categorySelect').append('<option value=' + this['category_id'] + '>' + this['category_name'] + '</option>');
                            });
                            $("#categorySelect option:last").attr('selected','selected');
                            console.log('新增成功');
                        }
                    }else{
                        alert('网络错误,请重试');

                    }

                    $('#addModal').modal('hide');
                    $('#category_name_input').val("");
                },
                "json"
            );

        });


        //实例化富文本编辑器
        var um = UM.getEditor('myEditor');

        //正则的样式
        $(function() {
            //1. 正则逻辑样式
            $("#addForm").validation({icon: true, reqmark: false});
            $("#basicInfoForm").validation({icon: true, reqmark: false});
        });

        $(function(){

            //点击显示模态框
            $('#addRank').click(function() {
                $('#rankModal').modal();

            });

            //点击显示模态框
            $('#choosePostageTemplateBtn').click(function() {
                //加载模板
                $.ajax({
                    url:"../postage-template/get-all",
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        $('#postageTemplates').empty();
                        $.each(data,function(){
                            $('#postageTemplates').append('<option value="'+this['id']+'" data-default-unit-price='
                                + this['default_unit_price'] +'>'+this['name']+'</option>');
                        });
                    }
                });

                //显示模态框
                $('#choosePostageTemplateModal').modal();

                //显示表格

                setTimeout(function() {
                    $('#postageTemplateDetailTable').datagrid({
                        title:'模板详情',
                        iconCls:'icon-edit',
                        width:$('#postageTemplateToolbox').outerWidth(true),
                        height:250,
                        singleSelect:true,
                        showFooter:true,
                        idField:'province_name',
                        url:'../postage-template/get-detail',
                        columns:[[
                            {field:'province_name',title:'省份',align:'center',
                                width:$('#postageTemplates').width() / 2},
                            {field:'unit_price',title:'单价',align:'center',editor:{type:'numberbox',options:{precision:2}},
                                width:$('#postageTemplates').width() / 2},
                        ]],
                        onEndEdit:function(index,row){
                            var select = $('.datagrid-row-selected').find('.filter-option.pull-left');
                            if (select.length > 0) {
                                row.province_name = select.text();
                            }
                        },
                        onBeforeEdit:function(index,row){
                            row.editing = true;
                            $(this).datagrid('refreshRow', index);
                        },
                        onAfterEdit:function(index,row){
                            if (row.province_name == null || row.province_name == "") {
                                alert('请选择省份')
                                $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                            } else {
                                row.editing = false;
                                $(this).datagrid('refreshRow', index);
                            }
                        },
                        onBeginEdit:function(index,row){
                            $('.selectpicker').selectpicker('render');
                        },
                        onCancelEdit:function(index,row){
                            if (row.province_name == null || row.province_name == "") {
                                alert('请选择省份')
                                $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                            } else {
                                row.editing = false;
                                $(this).datagrid('refreshRow', index);
                            }
                        },
                        onLoadSuccess:function(data){
                            var unit_price = $($('#postageTemplates')[0].options[$('#postageTemplates')[0].selectedIndex]).attr('data-default-unit-price');
                            if (unit_price) {
                                insert({"province_name":"全国","unit_price":unit_price});
                                $('#postageTemplateDetailTable').datagrid('endEdit', $('#postageTemplateDetailTable').datagrid('getRowIndex',
                                    $('#postageTemplateDetailTable').datagrid('getSelected')));
                            }
                        }
                    });
                    reload();
                }, 300);
            });

            $('body').on('change', '#postageTemplates', function(){
                reload();
            });

            //点击选择运费模板按钮
            $("body").on('click','#surePostageTemplateBtn',function(){
                if ($('#postageTemplateDetailTable').datagrid('getChanges').length > 0) {
                    alert('请保存修改内容')
                } else {
                    $('#postageTemplate').attr('value', $("#postageTemplates").val());
                    $('#postageTemplate').text($("#postageTemplates")[0].options[$("#postageTemplates")[0].selectedIndex].text);
                    $('#choosePostageTemplateModal').modal('hide');
                }
            });

            //删除图标显示hover事件
            $("body").on('mouseover mouseout','.attributeSet',function(){
                if(event.type == "mouseover"){
                    //鼠标悬浮
                    $(this).children("i").css("display","inline");
                }else if(event.type == "mouseout"){
                    //鼠标离开
                    $(this).children("i").css("display","none");

                }
            });

            //删除图标显示hover事件
            $("body").on('mouseover mouseout','.categorySet',function(){
                if(event.type == "mouseover"){
                    //鼠标悬浮
                    $(this).children("i").css("display","inline");
                }else if(event.type == "mouseout"){
                    //鼠标离开
                    $(this).children("i").css("display","none");

                }
            });


            //新建分类中属性添加按钮点击事件
            $('body').on('click','.newCategoryBtn',function(){
                //为空不操作
                if(!$(".categoryInput").val()){
                    return;
                }

                var attr_name = $(".categoryInput").val();
                //加载属性可选择项目
                $.ajax({
                    url: "add-attr",
                    data:{"category_id":$('#category_id_span').html(),"attr_name":attr_name},
                    dataType: "json",
                    success: function (data) {
                        if(data==='0'){
                            alert('填写信息有误,请检查');
                        }else {
                            $(".categoryInput").val("");
                            $('.categorySetDiv').append('<p class="label categorySet"> <span class="btn btn-default categoryBtn" id=attr_id' + data + '>' + attr_name + '</span> <i class="category_del"></i> </p>');
                        }
                    }
                });

            });

            //新建分类中属性添加按钮点击事件
            $('body').on('click','.newAttributeBtn',function() {
                //为空不操作
                if(!$(this).parent().prev().val()){
                    return;
                }

                console.log('$(".attributeInput").val()'+$(this).parent().prev().val());

                var attr_opt_name = $(this).parent().prev().val();

                $attr_id = $(this).parent().parent().prev().prev().attr('ID');
                var attr_id=$attr_id.substr(9);

                $that=$(this).parent().parent().prev();

                console.log('$attr_id'+attr_id);

                //加载属性可选择项目
                $.ajax({
                    url: "add-attr-opt",
                    data:{"attr_id":attr_id,"attr_opt_name":attr_opt_name},
                    dataType: "json",
                    success: function (data) {
                        if(data==='0'){
                            alert('填写信息有误,请检查');
                        }else {
                            $that.append('<p class="label  attributeSet"> <span class="btn btn-default attributeBtn" id=attr_opt_id'+data+'>'+attr_opt_name +'</span> <i class="sku_del" ></i> </p>');
                        }
                    }
                });

//            $(this).parent().parent().prev().append('<p class="label attributeSet">'+ '<span class="btn btn-default attributeBtn">'+$(this).parent().prev().val()+'</span>'+ '<i class="sku_del"></i>'+'</p>');
                //清空输入框原有内容
                $(".attributeInput").val('');

            });

            //删除按钮点击事件
            $("body").on('click','.category_del',function(){
                $('#attr_opt_id_input').val('');
                $('#removeAttrModal').modal();
                $attr_id=$(this).prev().attr('ID');
                $('#attr_id_input').val($attr_id);



            });

            //删除属性按钮点击事件
            $("body").on('click','.sku_del',function(){
                $('#attr_id_input').val('');
                $('#removeAttrOptModal').modal();
                $attr_opt_id=$(this).prev().attr('ID');
                $('#attr_opt_id_input').val($attr_opt_id);

            });

            $('#removeAttrOptBtn').click(function(){


                if($('#attr_opt_id_input').val()){
                    $attr_opt_id=$('#attr_opt_id_input').val();
                    var attr_opt_id=$attr_opt_id.substr(11);
                    //删除属性操作选择项目
                    console.log(attr_opt_id);

                    $.ajax({
                        url: "remove-attr-opt",
                        data:{"attr_opt_id":attr_opt_id},
                        dataType: "json",
                        success: function () {


                        }
                    });

                    //删除父元素 需要调接口
                    $id = '#'+$attr_opt_id;
                    $($id).parent().remove();
                    $('#removeAttrOptModal').modal('hide');
                    $('#attr_opt_id_input').val('');

                }


            });

            $('#removeAttrBtn').click(function() {


                if ($('#attr_id_input').val()) {
                    $attr_id = $('#attr_id_input').val();
                    var attr_id = $attr_id.substr(7);
                    //删除属性操作选择项目
                    $.ajax({
                        url: "remove-attr",
                        data: {"attr_id": attr_id},
                        dataType: "json",
                        success: function () {


                        }
                    });

                    //删除父元素 需要调接口
                    $id1 = '#' + $attr_id;
                    $($id1).parent().remove();
                    console.log($id1);
                    $('#removeAttrModal').modal('hide');
                    $('#attr_id_input').val('');

                }

            });

            //点击属性按钮高亮或者熄灭
            $("body").on('click','.attributeBtn',function(){
                if($(this).hasClass('btn-default')){
                    $(this).addClass('btn-info');
                    $(this).removeClass('btn-default');
                }else{
                    $(this).addClass('btn-default');
                    $(this).removeClass('btn-info');
                }
            });

            $("body").on('click','.categoryBtn',function(){
                if($(this).hasClass('btn-default')){
                    $(this).addClass('btn-info');
                    $(this).removeClass('btn-default');
                }else{
                    $(this).addClass('btn-default');
                    $(this).removeClass('btn-info');
                }
            });



            //点击选择属性按钮
            $("body").on('click','#sureCategoryBtn',function(){

                //遍历拿到已选的规格数组
                var arr=[];
                $('#rankDiv').children('div').children('p').each(function(){

                    arr.push($(this).text());
                    console.log(arr);

                });

                //规格遍历处理
                $('.categorySetDiv').children('p').children('span').each(function(){

                    if($(this).hasClass('btn-default')){

                        //删除规格
                        if($.inArray($(this).text(), arr)==-1){

                            console.log('没有选择的'+$(this).text()+'不做删除处理');

                        }else {
                            var attr_name = $(this).text();


                            $('.attrName').each(function(){

                                if($(this).text()==attr_name){

                                    $(this).parent().remove();
                                }

                            });

                            console.log('移除'+$(this).text());
                        }



                    }else if($(this).hasClass('btn-info')){


                        //新增规格
                        if($.inArray($(this).text(), arr)==-1){

                            var attr_name = $(this).text();
                            $attr_id = $(this).attr('ID');
                            var attr_id=$attr_id.substr(7);

                            console.log('attr_id'+attr_id);

                            //加载属性可选择项目
                            $.ajax({
                                url: "get-attr-opt-list-by-attr-id",
                                data:{"attr_id":attr_id},
                                dataType: "json",
                                success: function (data) {
                                    var strl = '<div><p class="attrName" id=attr_id_p'+attr_id+'>'+attr_name+'</p><div class="attributeSetDiv col-sm-12 col-md-12" style="margin-left: -15px;">';
                                    console.log(data);
                                    $.each(data, function () {
                                        var str = '<p class="label  attributeSet"> <span class="btn btn-default attributeBtn" id=attr_opt_id'+this['attr_opt_id']+'>'+this['attr_opt_name'] +'</span> <i class="sku_del" ></i> </p>';
                                        strl+=str;
                                        console.log(this['attr_opt_name']+'---->'+str);
                                    });
                                    $('#rankDiv').append(strl+'</div> <div class="input-group col-md-3 col-sm-3" style="padding-top: 15px;padding-bottom: 20px"> <input type="text" class="form-control attributeInput" placeholder="请输入商品属性" > <span class="input-group-btn"> <button class="btn btn-default newAttributeBtn" type="button" >新建</button> </span></div> </div>');
                                }
                            });
                            console.log('新增'+$(this).text());
                        }else{
                            console.log('已经存在'+$(this).text()+'不做新增处理');
                        }
                    }
                });
                $('#rankModal').modal('hide');
            });
        });

        function getRowIndex(target){
            var tr = $(target).closest('tr.datagrid-row');
            return parseInt(tr.attr('datagrid-row-index'));
        }
        function editrow(target){
            $('#postageTemplateDetailTable').datagrid('beginEdit', getRowIndex(target));
        }
        function deleterow(target){
            $.messager.confirm('Confirm','Are you sure?',function(r){
                if (r){
                    $('#postageTemplateDetailTable').datagrid('deleteRow', getRowIndex(target));
                }
            });
        }
        function saverow(target){
            $('#postageTemplateDetailTable').datagrid('endEdit', getRowIndex(target));
        }
        function cancelrow(target){
            $('#postageTemplateDetailTable').datagrid('cancelEdit', getRowIndex(target));
        }
        function insert(target){
            index = 0;
            if (!target) {
                target = {
                    "province_name" : "",
                    "unit_price": "0.00"
                };
                index = $('#postageTemplateDetailTable').datagrid('getRows').length;
            }
            $('#postageTemplateDetailTable').datagrid('insertRow', {
                index:index,
                row:target
            });
            $('#postageTemplateDetailTable').datagrid('selectRow',index);
            $('#postageTemplateDetailTable').datagrid('beginEdit',index);
        }
        function reload(){
            $('#postageTemplateDetailTable').datagrid('options').queryParams = {
                "template_id" :$("#postageTemplates").val()
            };
            $('#postageTemplateDetailTable').datagrid('reload');
        }


        //点击发布商品
        $('.publishBtn').click(function(){


            var pic_url_arr = [];
            //遍历得到url——arr
            $('.img-rounded').each(function(){
                $url=$(this).attr('src');
                if($url=="http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"){

                }else{
                    pic_url_arr.push($url);
                }
            });

            console.log(JSON.stringify(pic_url_arr));

            //正则提示写法
            if ($("#basicInfoForm").valid()==false){
                alert('填写信息有误,请检查');
                return false;
            }

            if ($('#commodity_price').val()<=0){
                alert('商品价格必须大于0');
                return false;
            }

            if ($('#postageTemplate').attr('value') == null || $('#postageTemplate').attr('value') == '') {
                alert('填写信息有误,请检查');
                $('#postageTemplateErrorMessage').show();
                return false;
            } else {
                $('#postageTemplateErrorMessage').hide();
            }

            if($('#is_hot').attr('checked')){
                var is_hot =1;
            }else{
                var is_hot =0;
            }

            //遍历拿到已选的规格数组
            var arr=[];
            var flag = true;
            $('#rankDiv').children('div').children('p').each(function(){
                var arr1=[];
                arr1.push($(this).attr('ID').substr(9));
                var arr2=[];
                $(this).next().children('p').children('span').each(function(){

                    if($(this).hasClass('btn-info')){
                        arr2.push($(this).attr('ID').substr(11));
                        flag = false;
                    };
                    console.log('$(this)--->'+$(this).attr('ID').substr(11));

                });

                arr1.push(arr2);
                arr.push(arr1);
                console.log(arr);
            });

            if(flag){
                alert('属性不能全不选');
                return false;
            }



            console.log(JSON.stringify(arr));

            var first_category = $("#chooseCategorySelect option:selected").val();//一级分类category_id
            var second_category = $("#categorySelect option:selected").val();//二级分类category_id

            var store_id = 1;//假数据

            var price = $('#commodity_price').val();
            var stock_num = $('#stock_num').val();
            var commodity_name = $('#commodity_name').val();
            var pro_id =$('#commodity_code').val();
            var pic_url = pic_url_arr[0];
            var banner_url = JSON.stringify(pic_url_arr);
            var content = getAllHtml();//文本详情
            var contentTrue = getContent();//内容

            var attr_opt_id = JSON.stringify(arr);

            if(!pic_url){
                alert('请上传商品主图(最少一张)');
                return false;
            }

            if(!contentTrue){
                alert('请编辑商品描述');
                return false;
            }

            //加载属性可选择项目
            $.ajax({
                type:'POST',
                data:{
                    "commodity_id":$('#commodity_id_input').val(),
                    "is_sale":$('#is_sale_input').val(),
                    "store_id":store_id,
                    "price":price,
                    "pic_url":pic_url,
                    "banner_url":banner_url,
                    "is_hot":is_hot,
                    "commodity_name":commodity_name,
                    "content":content,
                    "content_true":contentTrue,
                    "first_category":first_category,
                    "second_category":second_category,
                    "attr_opt_id":attr_opt_id,
                    "pro_id":pro_id,
                    "stock_num":stock_num,
                    "postage_template_id":$('#postageTemplate').attr('value')
                },
                dataType: "json",
                url: "edit",
                success: function (data) {

                    if(data=='0'){

                    }else{
                        alert('修改成功');
//                        window.location.reload();
                        window.history.go(-1);
                    }

                }
            });



        });

        //富文本获取所有Html
        function getAllHtml() {
            return UM.getEditor('myEditor').getAllHtml();
        }

        //获取输入内容
        function getContent() {
            return UM.getEditor('myEditor').getContent();
        }

        //使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容
        function getPlainTxt() {

            return UM.getEditor('myEditor').getPlainTxt();

        }

        //按钮的操作
        function insertHtml(value) {
            var v = value;
            console.log(value);

            um.execCommand('insertHtml', v)
        }

        function allowDrop(ev)
        {
            ev.preventDefault();
        }

        function drag(ev)
        {
            ev.dataTransfer.setData("Text",ev.target.id);
        }

        function drop(ev)
        {
            ev.preventDefault();
            var data=ev.dataTransfer.getData("Text");
            var origin = document.getElementById(data);
            if ($(origin).attr('src') != "http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg"
                &&
                $(ev.target).attr('src') != "http://58pic.ooopic.com/58pic/14/70/68/34858PIC6sf.jpg") {
                var targetSrc = $(ev.target).attr('src');
                $(ev.target).attr('src', $(origin).attr('src'));
                $(origin).attr('src', targetSrc);
            }
        }

    </script>

    <?php $this->endBody() ?>
    </body>
    </html>
<?php $this->endPage() ?>